<?php
include_once './application/application.php';

class Page_conceptions {

    public $action;
    public $error;
    public $conceptions;
    private $table = 'views_conception_list';

    /**
     *
     */
    public function __construct() {
        $this->action = Arr::getValue( $_POST, 'action', false );
        DB::connect();
        if ( !DB::state() )
            $this->error = DB::getError();
        $this->init();
    }

    public function __destruct() {
        
    }

    public function readConceptions() {
        return ConceptionsCollection::allSorted();
    }


    public function init() {
        $this->conceptions = $this->readConceptions();
    }

    
    private function htElement( &$value ) {
        $ch_html       = '';
        $delete_button = '';

        if ( $value->children != NULL )
            $ch_html = $this->htmlList( $value->children );
        else
            $delete_button = '<div class="dd3-delete">
                                <a data-action="delete" href="javascript:void(0);">Удалить</a>
                            </div>';

        return sprintf(
            '<li data-id="%d" data-name="%s" data-parent_id="%d" data-state="%d" class="dd-item dd3-item">
                  <div class="dd-handle dd3-handle">&ensp;</div>
                  <div class="dd3-content">
                      <div class="dd3-name">
                          <a data-action="update" href="javascript:void(0);">%s</a>
                      </div>
                      %s
                  </div>
                  %s
              </li>',
            (int)    $value->id,
            (string) $value->name,
            (int)    $value->parent_id,
            (int)    $value->state,
            (string) $value->name,
            (string) $delete_button,
            (string) $ch_html
        );
    }

    
    private  function htmlList( &$cs, $state = 1 ) {
        $ht = array();

        foreach ( $cs as &$value ) array_push( $ht, $this->htElement( $value ) );

            if ( $ht != NULL ) {
                return '<ol class="dd-list">'.join( "\n", $ht ).'</ol>';
            }
    }

    
    public function getHtmlList() {
        $list = $this->htmlList( $this->conceptions );
        $list = $list ? $list : '<div class="dd-empty">&ensp;</div>';
        return $list;
    }
    


    public function outPage() {
        $params = array();
        $params['list'] = $this->getHtmlList();
        $this->printOut( includeFile( APP_PAGE_PARTS . 'page_conceptions.php', $params ) );
    }
    
    private function call_new() {
        $J = new JSON();
        $J->debug = (object) array('method' => __METHOD__);
        $data = (object) array(
            'name' => (string)  $J->readVar( 'name' ),
            'id' => NULL
        );
        DB::query('BEGIN');
        if (!$res = DB::query("INSERT INTO `$this->table` (name, parent_id, priority) VALUES('$data->name', 0, 0)")) return $J->error( DB::getError() );
        $data->id = (int) DB::$mysqli->insert_id;
        if (!$this->check()) return $J->error( DB::getError() );
        if (!$res = DB::query('COMMIT')) return $J->error( DB::getError() );
        $J->id = $data->id;
        $J->name = $data->name;
        return $J;
    }
    
    
    
    private function call_update() {
        global $cnc_maxlenght;
        $J = new JSON();
        $J->debug = (object) array('method' => __METHOD__);
        $data = (object) array(
            "id"   => (integer) $J->readVar( 'id', 0 ),
            "name" => (string)  $J->readVar( 'name' )
        );
        $cnc_maxlenght = 150;
        $validateTips = $this->validate($data->name, $cnc_maxlenght);
        
        if ($validateTips) return $J->error($validateTips);
        $J->conceptions  = $this->conceptions;
        if ($J->validateTips != null) return $J;
        $J->id = $data->id;
        $J->name = $data->name;
        $query = sprintf(
            "UPDATE `$this->table` SET name = '%s' WHERE id = %d LIMIT 1",
            $data->name,
            $data->id
        );

        if ( $res = DB::query( $query ) )
            $J->mysql_result = 'OK';
        else return $J->error( DB::getError() );
        if ($data->id == 0) {
            $J->id = (int) DB::$mysqli->insert_id;
            $J->name = $data->name;
        }
        return $J;
    }

    
    
    private function validate($data, $maxlenght) {
        $validateTips = array();
        if (mb_strlen($data) > $maxlenght) array_push(
            $validateTips,
            "Длинна поля не более $maxlenght символов."
        );
        return ($validateTips) ? sprintf('<div>%s</div>', join('<\ br>', $validateTips)) : FALSE;
    }

    
    
    private function call_move() {
        $J = new JSON();
        $J->debug = (object) array('method' => __METHOD__);
        $data = (object) array(
            "id"        => (integer) $J->readVar( 'id', 0 ),
            "parent_id" => (integer) $J->readVar( 'parent_id', 0 ),
            "priority"  => (integer) $J->readVar( 'priority', 0 )
        );
        $q = sprintf(
            "SET @obj_id  = %d, @obj_priority = %d, @obj_parent_id = %d;
            BEGIN;
              SELECT priority INTO @old_priority FROM $this->table WHERE id = @obj_id LIMIT 1;
              SELECT parent_id INTO @old_parent_id FROM $this->table WHERE id = @obj_id LIMIT 1;
              UPDATE `$this->table` SET priority = priority - 1 WHERE parent_id = @old_parent_id AND priority > @old_priority;
              UPDATE `$this->table` SET priority = priority + 1 WHERE parent_id = @obj_parent_id AND priority >= @obj_priority;
              UPDATE `$this->table` SET parent_id = @obj_parent_id, priority = @obj_priority WHERE id = @obj_id;
            COMMIT",
            $data->id, $data->priority, $data->parent_id
        );


        $q = explode(';', $q);
        $q = array_map('trim', $q);
        foreach($q as &$query) {
                if (!$res = DB::query($query)) return $J->error(DB::getError());
        }
        $this->conceptions   = $this->readConceptions();
        /*$J->conceptions    = $this->conceptions;
        $J->conceptions_html = $this->getHtmlList();*/

        $J->id          = $data->id;
        $J->parent_id   = $data->parent_id;
        $J->priority    = $data->priority;

        return $J;
    }

    private function call_delete() {
        $J = new JSON();
        $data = (object) array(
            "id" => (integer) $J->readVar( 'id' )
        );
        DB::query('BEGIN');
        DB::query(sprintf(
            "DELETE FROM $this->table WHERE
                id = %d AND
                id NOT IN (
                    SELECT DISTINCT id
                    FROM (
                      SELECT ch.parent_id AS id
                      FROM $this->table cl
                      INNER JOIN $this->table
                        AS ch ON (cl.id = ch.parent_id)
                    ) AS conceptions
                )",
            $data->id
        ));
        if (!$this->check()) return $J->error( DB::getError() );
        if ($res = DB::query('COMMIT')) $this->conceptions = $this->readConceptions();
        else return $J->error( DB::getError() );
        $J->id = $data->id;
        return $J;
    }

    private function check($id = FALSE){
        $pid = ($id) ? "( SELECT parent_id FROM `views_conception_list` WHERE id = $id LIMIT 1 )" : "0";
        DB::query("SET @t1 = 0");
        return DB::query("UPDATE `views_conception_list` SET `priority` = (@t1 := IFNULL(@t1, 0) + 1)
                 WHERE `parent_id` = $pid ORDER BY `priority`");
    }

    public function call( $method = FALSE ) {
        $method = ( $method ) ? $method : $this->action;
        $method = explode( '_', $method, 2 );
        $method = 'call_'.strtolower( $method[1] );
        if(method_exists($this, $method)) print call_user_func(array($this, $method));
    }

    public function printOut( $content = '' ) {
        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm( true );
        $params = array(
            'leftmenu'  => Navbar::getVerticalBar( 'leftmenu' ),
            'content'   => $content ? $content : ''
        );

        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }


}



$page = new Page_conceptions();

Navbar::$expanded = 'lm-sys-web';

if ( $page->action ) print $page->call();
else {
    if ( !Auth::isLogged() ) reLocate ( 'index.php' );
    switch ( $_SERVER['QUERY_STRING'] ) {
    default:
        Navbar::$active   = 'lm-conceptions';
        $page->outPage();
        break;
    }
}
?>
